<template>
    <div class="comment-input-box" v-if="status">
        <div class="comment-bar" v-if="!isEdit">
            <div class="left" @click="showEdit">
                <i class="uicon uicon-com-edit"></i>
                {{count == 0 ? '抢沙发...' : '写评论'}}
            </div>
            <div class="right">
                <a href="javascript:;" @click="countClick" class="com-count" v-if="from !== 'comment' && from !=='hidden'">
                    <i class="uicon" :class="iconClass"></i>
                    <label>{{comText}}</label>
                </a>
                <a href="javascript:;" class="com-share" v-else>
                    <i class="uicon uicon-img"></i>
                </a>
            </div>
        </div><!-- end comment-bar -->
        <ui-popup :status="isEdit" @close="isEdit = false">
            <transition name="slide-in-up">
                <form  action="#" onsubmit="return false" class="comment-input" v-if="isEdit">
                    <div class="comment-cont">
                        <textarea ref="editor" v-model.trim="content" :placeholder="placeholder"  @keypress.enter="submit"></textarea>
                        <div class="upload-img" v-if="image.length>0">
                            <img :src="image[0]" @click="previewImage"/>
                            <a href="javascript:;" @click="removeImage"><i class="close"></i></a>
                        </div>
                    </div>
                    <div class="tool">
                        <div class="tools">
                            <a href="javascript:;">
                                <i class="uicon uicon-camera"></i>
                                <div class="upload-btn upload-camera"></div>
                            </a>
                            <a href="javascript:;">
                                <i class="uicon uicon-img"></i>
                                <div class="upload-btn upload-img"></div>
                            </a>
                        </div>
                        <a href="javascript:;" :class="{'on':content.length>0}" @click="submit">发送</a>
                    </div>
                </form><!-- end comment-input -->
            </transition>
        </ui-popup>
        
        <ui-preview :config="preview" v-if="preview.status" @close="preview.status = false"/>
    </div><!-- end commont-input -->
</template>
<script>
import Popup from "./popup.vue";
import uiPreview from '../components/preview.vue'
//去除file的cameras设置
function removeInputCapture(selector){
    let pick = document.querySelector(selector + ' input[type=file]');
    if(!pick){
        setTimeout(()=>{
            removeInputCapture(selector);
        },300)
        return false;
    }

    pick.removeAttribute('capture');
}

export default {
    name:'ui-comment',
    components: {
        [Popup.name]: Popup,
        [uiPreview.name]:uiPreview,
    },
    data(){
        return {
            isEdit:false,
            status:false,
            posting:false,
            from:'detail', //detail:新闻详情 ，news新闻评论列表 comment:评论详情
            type:'add', // add:新闻  reply:评论
            info:{},//如果是评论新闻，这里是新闻的信息，如果是回复评论，这里就是回复的评论的信息
            count:0,
            placeholder:'',
            content:'',
            upload_image:[],
            image:[],
            uploader:'',
            isShowComment:false,//是否滚动到评论列表

            preview:{
                status:false,
                delete:false,
                active:0,
                list:[]
            },
        }
    },
    computed:{
        comText(){
            let text = '';
            if(this.isShowComment || this.from == 'news'){
                text = '正文'
            }else{
                if(this.count == 0){
                }else if(this.count >= 10000){
                    let num = (this.count/10000).toFixed(1);
                    text = num;
                    if(num[num.length-1] == 0){
                        text = parseInt(num);
                    }
                    text = text + '万';
                }else{
                    text = this.count
                }
            }
            return text;
        },
        iconClass(){
            if(this.isShowComment || this.from == 'news'){
                return 'uicon-com-text'
            }else{
                if(!this.count || this.count < 1000){
                    return 'uicon-com-hot';
                }else if(this.count>=1000 && this.count < 10000){
                    return 'uicon-com-hot-1';
                }else{
                    return 'uicon-com-hot-2';
                }
            }
        }
    },
    mounted(){
        this.$on('init',(param)=>{
            if(param.type !== 'add' && param.type !== 'reply') return false;
            if(param.type == 'add'){
                this.placeholder = '优质评论将会被优先展示';
            }else{
                this.placeholder = '回复 ' + param.info.member_nickname;
            }

            this.from = param.from || 'detail';
            this.type = param.type;
            this.info = param.info;
            !isNaN(param.count) && (this.count = param.count);
            this.status = true;
            if(this.from == 'detail'){
                let commentEl = document.querySelector('.comment-list');
                commentEl && window.addEventListener('scroll',(e)=>{
                    let winH = window.innerHeight;
                    let rect = commentEl.getBoundingClientRect();
                    this.isShowComment = rect.top< winH;
                },false);
            }
            
        });
        this.$on('edit',(param)=>{
            if(param.type !== 'add' && param.type !== 'reply') return false;
            if(param.tye == 'add'){
                this.placeholder = '优质评论将会被优先展示';
            }else{
                this.placeholder = '回复 ' + param.info.member_nickname;
            }
            this.type = param.type;
            this.info = param.info;
            this.isEdit = true;
        });

        this.uploader = WebUploader.create({
            // 选完文件后，是否自动上传。
            auto: true,
            // 文件接收服务端。
            server: this.$config.api + "?ct=upload&ac=index",
            // pick: ".upload-btn",
            // 只允许选择图片文件。
            accept: {
                title: "Images",
                extensions: "gif,jpg,jpeg,bmp,png",
                mimeTypes: "image/*",
                
            },
            chunked: true,
            chunkSize: 1 * 1024 * 1024,
            formData: {
                file: "file",
            }
        });
        this.uploader.on("uploadBeforeSend", (object, data, headers) => {
            headers["X-Requested-With"] = "XMLHttpRequest"
            data.guid = object.file.guid;
        });

        // 上传成功
        this.uploader.on("uploadSuccess", (file, response) => {
            var res = JSON.parse(response._raw);
            this.image.splice(0,1,res.data.filelink);
            this.upload_image.splice(0,1,res.data.filename);
        });

       
        // function removeInputCapture(){
        //     let pick = document.querySelector('.upload-btn input[type=file]');
        //     if(!pick){
        //         setTimeout(()=>{
        //             removeInputCapture();
        //         },300)
        //         return false;
        //     }

        //     pick.removeAttribute('capture');
        // }
        // removeInputCapture();

       // 图片不能大于2M
        this.uploader.on("beforeFileQueued", file => {
            // if (file.size > 2 * 1024 * 1024) {
            //     _this.$toast("图片不能超过2M");
            //     return false;
            // }

            file.guid = WebUploader.Base.guid();
        });

        
    },
    methods:{
        countClick(){
            if(this.from == 'news'){
                location.href = this.$config.pages.detail + '?id=' + this.info.id;
            }else{
                 if(this.isShowComment){
                     document.documentElement.scrollTop = document.body.scrollTop = 0;
                 }else{
                    location.href = this.$config.pages.comment + '?type=news&id=' + this.info.id;
                 }
            }
        },
        showEdit(){
            this.isEdit = true;
            this.$nextTick(()=>{
                this.$refs.editor.focus();
                this.uploader.addButton({
                    id: '.upload-camera',
                    multiple:false,
                    innerHTML: ''
                });
                this.uploader.addButton({
                    id: '.upload-img',
                    multiple:false,
                    innerHTML: ' '
                });

            
                removeInputCapture('.upload-img');
            })
        },
        submit(){
            if(this.content.length <= 0) return false;
            if(this.type == 'add'){
                let co = this.post('?ct=comment&ac=add_comment',{
                    foreign_id:this.info.id,
                    content:this.content,
                    type:this.info.type || 1, // 会员发布是2，会在传进来，新闻是1，默认不会传
                    image:this.upload_image.join(','),
                });
                co && co.then(rs=>{
                    this.done(rs);
                })
            }else if(this.type == 'reply'){
               let co = this.post('?ct=comment&ac=reply_comment',{
                    comment_id:this.info.id,
                    content:this.content,
                    type:this.info.type || 1, // 会员发布是2，会在传进来，新闻是1，默认不会传
                    image:this.upload_image.join(','),
                });
                co && co.then(rs=>{
                    this.done(rs);
                })
            }
        },
        post(url,param){
            if(this.posting) return false;
            this.posting = true;
            return this.$http.post(url,param).then(response=>{
                let {data} = response;
                if(data.code == 0){
                    return data.data;
                }else{
                    this.$toast(data.msg);
                }
            }).catch(e=>{
                this.$toast('操作失败');
            }).finally((()=>{
                this.posting = false;
            }))
        },
        done(rs){
            this.$toast('评论成功');
            this.$emit('done',rs);
            this.count++;
            this.isEdit = false;
            this.content = '';
            this.image = [];
            this.upload_image = [];
        },
        //图片预览
        previewImage(){
            if(this.image.length == 0) return false;
            this.preview.active = 1;
            this.preview.list = this.image
            this.preview.status = true;
        },
        removeImage(){
            this.image=[]
            this.upload_image=[]
        }
    }
}
</script>
<style lang="less">
// html,body {
//     background-color:#fff;
// }
.comment-input-box {
    position: fixed;
    bottom:0;
    left:0;
    right:0;
    margin:auto;
    z-index:1000;
    .ui-preview {
        z-index:100000;
    }
    &.comment-edit {
        top:0;
        &::before {
            content: '';
            position: absolute;
            top:0;
            left:0;
            bottom:0;
            right:0;
            background-color:rgba(0,0,0,.5);
        }
    }
}
.comment-bar {
    height:104px;
    border-top:1px solid #eee;
    background-color:#fff;
    color:#282828;
    line-height: 1;
    &,
    .right {
        display:flex;
        justify-content: space-between;
        align-items: center;
    }
    .left {
        flex:1;
        padding-left:40px;
        font-size:32px;
        i {
            margin-right:12px;
        }
    }
    .right {
        height:100%;
        font-size:28px;
    }
    .left,a {
        display: flex;
        align-items: center;
        height:100%;

    }
    .com-count {
        padding:0 40px;
    }
    .com-count i {
        top:2px;
    }
    .com-count label {
        margin-left:12px;
        align-items: center;
        vertical-align: middle;
    }
    .com-share {
        padding:0 40px;
    }
}
.comment-input {
    position:absolute;
    top:0;
    right:0;
    left:0;
    margin:auto;
    padding:30px;
    background-color:#fff;
    z-index: 1;

    textarea {
        border:none;
        outline: none;
        resize: none;
        display: block;
        padding:20px 10px;
        width:100%;
        font-size:28px;
        border-radius: 4px;
        background-color:#f7f7f7;

        caret-color: #e64a19;
        &::-webkit-input-placeholder {
            color: #c6c6c6;
        }
    }
    .tool {
        margin-top:20px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        .tools {
            display: flex;
            flex-wrap: nowrap;
            align-items: center;
            flex:1;
            white-space: nowrap;
            overflow-y: hidden;
            overflow-x:auto;
            a {
                flex-shrink: 0;
                flex-grow: 0;
                padding-right:34px;
                position: relative;

                .upload-btn {
                    position: absolute;
                    top:0;
                    left:0;
                    bottom:0;
                    right: 0;
                    opacity: 0;
                    div {
                        width:100%;
                        height:100%;
                    }
                }
            }
            a + a {
                padding-left:34px;
            }
        }
        &>a {
            &.on {
                background-color:#e64a19;
                border-color:#e64a19;
                color:#fff;
            }

            display: flex;
            justify-content: center;
            align-items: center;
            flex-shrink: 0;
            flex-grow: 0;
            width:112px;
            height:54px;
            border:3px solid #e2e2e2;
            color:#919191;
            font-size:28px;
            border-radius: 4px;
        }
    }
}
.comment-cont {
    display: flex;
    height:118px;
    overflow: hidden;
    background-color:#f7f7f7;

    textarea {
        flex:1;
        height: 100%;
    }
    .upload-img {
        display: flex;
        padding:6px;
        justify-content: space-between;
        align-items: center;
        margin-left:30px;
        width:158px;
        height:100%;

        img {
            display: block;
            width:106px;
            height:auto;
        }

        a {
            display: flex;
            justify-content: center;
            align-items: center;
            padding-left:15px;
            padding-right:9px;
            height: 100%;
        }
    }

    .close {
        display: block;
        box-sizing: content-box;
        color:#dcdcdc;
        width:20px;
        height:20px;
        position:relative;
        overflow: hidden;
        
        &::before,
        &::after {
            content:'';
            position: absolute;
            background-color:#dcdcdc;
            // transform: translate(-50%,-50%);
        }

        &::before {
            width:2px;
            height:20px;
            right:10px;
            transform: translateX(50%) rotate(45deg);
        }
        &::after {
            top:10px;
            width:20px;
            height:2px;
            transform: translateY(-50%) rotate(45deg);
        }
    }
}
</style>

